
// pages/chat/chat.js
const db = wx.cloud.database();

const _ = db.command;

Page({

  /**
  * 页面的初始数据
  */
  data: {
    // 接收者基本信息
   receivebaseInfo:{},
   sendAvatar:'',
  newsList:[],//消息列表
  read:[],
  unread:[],
  input:null,
  openid:null,
  inputShowed: false,
  scrollTop: 0,
  inputBottom: '0px',

  scrollid:'scrollid',
  scrollHeight:'420px',
 //  下拉刷新
  triggered:false,
 //  历史记录当前页
  pageNo: 1,
  list:[],
  user:{},
  acceptor:{},
  },

  // 发送信息
 async send(e)
  {  
      const{user} = this.data;
      const{acceptor} = this.data;
        if(this.data.input==null){
            return 0;
        }
    // 生成消息
      this.setData({
        ['message.sendid']:user._id,
        ['message.text']:this.data.input,
        ['message.date']:new Date(),
        ['message.state']:false
      })
      const{message} = this.data
    //发送
    if(message.text.length==0)
    {
        return 
    }
      await db.collection('chatlist').where({
        _id:_.or([acceptor._id+user._id,user._id+acceptor._id])
        }).update({
            data:{
                chat:_.push(message)
            }
        }).then(res=>{
        })

      this.setData({
        scrollid:'scrollid'+ (this.data.newsList.length-1)
      })
      
    //清空输入框
       this.setData({
         input:''  
        })

  },

  bindChange(e){
    this.setData({
      input:e.detail.value
    })
  },
refresh(){
    setTimeout(()=>{  this.setData({
        triggered:false
    })},1000)  

   
},
 onLoad:async function (options) { 
    var that = this;
    //发送方信息
    var user = wx.getStorageSync('userFlag').user;
    //接收方信息：
    var id = options.id;
    var acceptor={}
    await db.collection('user').where({
        _id:id
    }).get().then(res=>{
        acceptor = res.data[0]
    })
    if(!acceptor){
        wx.showToast({
          title: '用户不存在',
        })
    }
    var relation ;
    //查找关系是否存在
    await db.collection('chatlist').where({
        _id:_.in([user._id+id,id+user._id])
    }).get().then(res=>{
       relation = res.data[0];
    })

    if(!relation){
        //关系不存在，添加关系。
        await db.collection('chatlist').add({
            data:{
                _id:user._id+id,
                user1:user,
                user2:acceptor,
                chat:[]
            }
        }).then(res=>{
        });

        await db.collection('chatlist').where({
            _id:_.in([id+user._id,user._id+id])
        }).get().then(res=>{
           relation = res.data[0];
        })
    }else{
        // 关系存在，将未读设置为已读；
        var chat = relation.chat;
        for(var i = 0;i<chat.length;i++){
            if(chat[i].sendid==acceptor._id){
                chat[i].state=true;
            }
        }
       await db.collection('chatlist').where({
        _id:_.in([id+user._id,user._id+id])
       }).update({
           data:{
               chat:chat
           }
       }).then(res=>{
            console.log(res);
       })
    }

    that.setData({
        user:user,
        acceptor:acceptor
    })

    wx.setNavigationBarTitle({
        title:acceptor.name,
    })

    const watcher = db.collection('chatlist').where({
        _id:_.or([id+user._id,user._id+id]),
    }).watch({
        onChange:res=>{
            this.setData({
                list:res.docs[0].chat
            })
            var x=this.data.list.length-1;
            var start=0;
            var end=0;
            for(;x>=0;x--)
            {
                if((this.data.list[x].state)&&(this.data.list[x].sendid!=this.data.user._id))
                {
                  start=x;
                    end=start-(20-(this.data.list.length-1-start))>0?start-(20-(this.data.list.length-1-start)):0;
                    break;
                }
                else
                { 
                     start=x;
                    if(x==0)
                    {
                        start=-1
                    }
                }
            }
            this.setData({
                unread:this.data.list.slice(end,start+1),
                newsList:this.data.list.slice(start+1,this.data.list.length)
            }) 
            if(this.data.newsList.length-1>=0)
            {
                 this.setData({
             scrollid:'scrollid'+ (this.data.newsList.length-1)
              })
            }
            else{
                this.setData({
                    scrollid:'history'+ (this.data.unread.length-1)
                })
            }
        },
        onError:err=>{
            console.log(err)
        }
    })
    
 },

 })